package com.zhxh.nzpos.sell;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.api.ConnectorSale;
import com.zhxh.nzpos.api.exception.AuthenticationException;
import com.zhxh.nzpos.api.exception.AuthorizationException;
import com.zhxh.nzpos.api.exception.CommunicationException;
import com.zhxh.nzpos.dao.SelloutDao;
import com.zhxh.nzpos.dao.StockDao;
import com.zhxh.nzpos.model.Sellout;
import com.zhxh.nzpos.serialport.PrintSerialPort;
import com.zhxh.nzpos.utils.PersistenceUtil;
import com.zhxh.nzpos.utils.ViewUtil;

/**
 * 商品销售的结算界面
 * 
 * @author wangzt
 * 
 */
public class SettleAccountActivity extends PrintSerialPort {

	private static final int SETTLE_SUCCESS = 1;
	private static final int SETTLE_FAIL = 2;

	private float total;// 总价
	private int totalPoints; // 累计积分
	private float collected;

	private String noteId;

	private SelloutDao selloutDao;
	private StockDao stockDao;
	private String card;
	

	SendingThread mSendingThread;

	private ArrayList<Sellout> sellouts;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == SETTLE_SUCCESS) {
				ViewUtil.makeToast(getApplication(), "付款成功");
				finish();
			} else {
				ViewUtil.makeToast(getApplication(), "付款失败");
			}
			ViewUtil.cancelProgressDialog();
		}

	};

	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sell_settle_account);
		Serializable extra = getIntent().getSerializableExtra(
				Constants.SELL_OUT_EXTRA);
		
		SharedPreferences sharedata = getSharedPreferences("PreferencesFile", 0);  
		card = sharedata.getString("cardId", null); 
		
		sellouts = (ArrayList<Sellout>) extra;

		selloutDao = new SelloutDao(getApplicationContext());
		stockDao = new StockDao(getApplicationContext());
		/*
		 * if (mSerialPort != null) {
		 * System.out.println("serial is not null/...........................");
		 * mSendingThread = new SendingThread(); mSendingThread.start(); } else
		 * { System.out.println("serial is null/..........................."); }
		 */
		initViews();
	}

	private void initViews() {
		TextView cardView = (TextView) findViewById(R.id.member_card_tv);
		card = getIntent().getStringExtra(Constants.MEMBER_CARD);
		noteId = getIntent().getStringExtra(Constants.SELL_NOTE_ID);

		if (card != null) {
			cardView.setText(getResources().getString(R.string.member_card)
					+ card);
		}
		int thePoints = 0;
		for (Sellout sellout : sellouts) {
			total += sellout.getTotal();
			thePoints += sellout.getTotalPoints();
		}

		TextView totalView = (TextView) findViewById(R.id.total_account);
		totalView.setText("" + total);
		TextView discountView = (TextView) findViewById(R.id.goods_discount);
		discountView.setText("0");
		TextView discountMoneyView = (TextView) findViewById(R.id.money_after_discount);
		discountMoneyView.setText("" + total);

		final TextView zhaolingView = (TextView) findViewById(R.id.zhaoling);// 找零
		zhaolingView.setText("0");

		TextView thePointsView = (TextView) findViewById(R.id.the_integral_tv);// 本次积分
		thePointsView.setText("" + thePoints);

		TextView totalPointsView = (TextView) findViewById(R.id.total_integral_tv);// 累计积分
		totalPointsView.setText("" + totalPoints);// TODO

		EditText collectedET = (EditText) findViewById(R.id.collected_money);
		collectedET.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// if (actionId == EditorInfo.IME_ACTION_DONE) {
				String cStr = ((EditText) v).getText().toString();
				try {
					collected = Float.parseFloat(cStr);
					if (total < collected) {
						float zl = collected - total;
						zhaolingView.setText("" + zl);
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				// }
				return false;
			}
		});

		//final CheckBox shouldPrint = (CheckBox) findViewById(R.id.no_print_doc_cb);

		Button okBtn = (Button) findViewById(R.id.deal_settle_account_btn);
		okBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (collected >= total) {
					ViewUtil.showProgressDialog(SettleAccountActivity.this,
							"正在处理...");
					new Thread() {
						public void run() {
							if (selloutDao.sellAll(sellouts, totalPoints)) {
								//if (!shouldPrint.isChecked()) {
									if (mSerialPort != null) {
										mSendingThread = new SendingThread();
										mSendingThread.start();
									} else {
										System.out
												.println("serial is null/...........................");
									}
							//	}
								ConnectorSale connectorSale = new ConnectorSale();
								try {
									for (Sellout sellout : sellouts) {
										connectorSale
												.submitSaleInfo(
														sellout,
														PersistenceUtil
																.getPosId(getApplicationContext()),
														PersistenceUtil
																.getOperatorCard(getApplicationContext()),
														card);
									}
								} catch (CommunicationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (AuthorizationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (AuthenticationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								handler.sendEmptyMessage(SETTLE_SUCCESS);
							} else {
								handler.sendEmptyMessage(SETTLE_FAIL);
							}
						}

					}.start();
				} else {
					ViewUtil.makeToast(getApplication(), "未付全款");
				}
			}
		});
		Button cancelBtn = (Button) findViewById(R.id.deal_cancel_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}

	/*
	 * 打印小票
	 */

	protected void onPrint(OutputStream mOutputStream) throws IOException {

		// TODO 按照格式补全打印信息
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");

		mOutputStream.write(("      大兴农资安全监管系统\r\n").getBytes("gbk"));
		mOutputStream.write(("     采育镇利民农资物资店\r\n").getBytes("gbk"));
		String h1 = "机号：LQ28    订单号：" + noteId + " \r\n";
		String h2 = "收银员：001   日期：" + simpleDateFormat.format(new Date())
				+ "\r\n";

		mOutputStream.write(h1.getBytes("gbk"));
		mOutputStream.write(h2.getBytes("gbk"));
		mOutputStream
				.write("================================\r\n".getBytes("gbk"));
		mOutputStream.write("商品名称     数量  单价  金额\r\n".getBytes("gbk"));
		/*
		 * mOutputStream.write("化肥         2    34   68.0\r\n".getBytes("gbk"));
		 * mOutputStream.write("化肥 份       2    34   68.0\r\n".getBytes("gbk"));
		 * mOutputStream.write("农药六六粉课   1    22   22.0\r\n".getBytes("gbk"));
		 */
		// String h3 = "农药六六粉课添加家（20%）";
		/*
		 * if(h3.getBytes().length > 16){ if(h3.length() <=8) { int j = 16 -
		 * h3.getBytes().length; while(j > 0){ h3 = h3.concat(" "); j--; }
		 * mOutputStream
		 * .write((h3+"12"+"     "+"23.3"+"    ""435.3\r\n").getBytes("gbk")); }
		 * else { String name1 = h3.substring(0,7); String name2 =
		 * h3.substring(8);
		 * mOutputStream.write((name1+sellout.getCount()+"     "
		 * +sellout.getPrice
		 * ()+"    "+sellout.getTotal()+"\r\n").getBytes("gbk"));
		 * mOutputStream.write((name2+"\r\n").getBytes("gbk")); } }
		 */

		int amount = 0;
		for (Sellout sellout : sellouts) {
			amount += sellout.getCount();
			String name = sellout.getGoodsName().trim();
			mOutputStream.write((name + "\r\n").getBytes("gbk"));
			mOutputStream.write(("              " + sellout.getCount() + "    "
					+ sellout.getPrice() + "  "
					+ sellout.getTotal() + "\r\n").getBytes("gbk"));
/*			if (name.length() <= 7 && name.getBytes().length <= 14) {
				int j = 14 - name.getBytes().length;
				while (j > 0) {
					name = name.concat(" ");
					j--;
				}
				mOutputStream
						.write((name + sellout.getCount() + "   "
								+ sellout.getPrice() + "   "
								+ sellout.getTotal() + "\r\n").getBytes("gbk"));
			} else {
				String name1 = name.substring(0, 7);
				String name2 = name.substring(7);
				mOutputStream
						.write((name1 + sellout.getCount() + "   "
								+ sellout.getPrice() + "   "
								+ sellout.getTotal() + "\r\n").getBytes("gbk"));
				mOutputStream.write((name2 + "\r\n").getBytes("gbk"));
			}*/

		}

		mOutputStream.write("===============================\r\n"
				.getBytes("gbk"));
		mOutputStream.write(("数量:      " + amount + "\r\n").getBytes("gbk"));
		mOutputStream.write(("应付货款:  " + total + "\r\n").getBytes("gbk"));

		mOutputStream.write(("收款:      " + collected + "   \r\n").getBytes("gbk"));
		mOutputStream.write(("找零:      " + (collected - total) + "       \r\n")
				.getBytes("gbk"));
		if(card != null && card.length() != 0)
			mOutputStream.write(("积分卡号： "+card+"    \r\n").getBytes("gbk"));
		else {
			mOutputStream.write(("积分卡号：  无    \r\n").getBytes("gbk"));
		}
		mOutputStream.write(("==========="
				+ simpleDateFormat2.format(new Date()) + "=============\r\n")
				.getBytes("gbk"));
		mOutputStream.write("           欢迎再次光临   \r\n ".getBytes("gbk"));
		mOutputStream.write("\r\n\r\n".getBytes());

		/*
		 * mOutputStream.write(("农资分销系统 "+noteId+"\n").getBytes("gbk"));
		 * mOutputStream.write(("总价：   "+total).getBytes("gbk"));
		 * mOutputStream.write(("收款：   "+collected).getBytes("gbk"));
		 * mOutputStream.write(("找零：   "+(collected-total)).getBytes("gbk"));
		 * mOutputStream
		 * .write("商品 名称      数量        单价     金额".getBytes("gbk"));
		 * 
		 * for (Sellout sellout : sellouts) {
		 * mOutputStream.write((sellout.getGoodsName
		 * ()+"     "+sellout.getCount()
		 * +"       "+sellout.getTotal()).getBytes("gbk"));
		 * 
		 * }
		 */
	}

	private class SendingThread extends Thread {
		@Override
		public void run() {
			while (!isInterrupted()) {
				try {
					if (mOutputStream != null) {
						onPrint(mOutputStream);
						/*
						 * mOutputStream.write("         农资分销系统\r\n".getBytes("gbk"
						 * ));
						 * System.out.println("================图片传输开始=============="
						 * );
						 * 
						 * mOutputStream.write("机号：LQ28    订单号：3836 \r\n".getBytes
						 * ("gbk"));
						 * mOutputStream.write("收银员：001   日期：2012.10.15\r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("=============================\r\n"
						 * .getBytes("gbk"));
						 * 
						 * 
						 * 
						 * //
						 * mOutputStream.write("=================\r\n".getBytes
						 * ());
						 * mOutputStream.write("商品名称   数量   单价   金额\r\n".getBytes
						 * ("gbk"));
						 * mOutputStream.write("化肥         2    34   68.00\r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("农药         1    22   22.00\r\n"
						 * .getBytes("gbk"));
						 * 
						 * mOutputStream.write("==============================\r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("数量：3\r\n".getBytes("gbk"));
						 * mOutputStream
						 * .write("应付货款：88.00\r\n".getBytes("gbk"));
						 * 
						 * mOutputStream.write("收款：  100.00    \r\n".getBytes("gbk"
						 * ));
						 * mOutputStream.write("找零：  12.00       \r\n".getBytes
						 * ("gbk"));
						 * mOutputStream.write("积分卡号： 8801038623334    \r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("===========16：44：33========\r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("           欢迎再次光临   \r\n "
						 * .getBytes("gbk"));
						 * mOutputStream.write("       服务电话：83523232\r\n"
						 * .getBytes("gbk"));
						 * mOutputStream.write("\r\n\r\n".getBytes());
						 */
						return;
					} else {
						return;
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		// TODO Auto-generated method stub

	}
}
